<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="交易姓名" prop="borrower">
        <el-input
          v-model="queryParams.borrower"
          placeholder="请输入交易姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="borrowerNick">
        <el-input
          v-model="queryParams.borrowerNick"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借/还款时间">
        <el-date-picker
          v-model="daterangeBorrowReturnTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="借/还款方式" prop="borrowReturnMethod">
        <el-select v-model="queryParams.borrowReturnMethod" placeholder="请选择借/还款方式" clearable>
          <el-option
            v-for="dict in dict.type.qiu_borrow_return_method"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入说明"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记账类型" prop="recordType">
        <el-select v-model="queryParams.recordType" placeholder="请选择记账类型" clearable>
          <el-option
            v-for="dict in dict.type.qiu_accounting_record_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="borrowerPhone">
        <el-input
          v-model="queryParams.borrowerPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['base:record:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="交易姓名" align="center" prop="borrower" />
      <el-table-column label="联系电话" align="center" prop="borrowerPhone" />
      <el-table-column label="昵称" align="center" prop="borrowerNick" />
      <el-table-column label="借/还款时间" align="center" prop="borrowReturnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.borrowReturnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借/还款方式" align="center" prop="borrowReturnMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qiu_borrow_return_method" :value="scope.row.borrowReturnMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="description" />
      <el-table-column label="记账类型" align="center" prop="recordType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qiu_accounting_record_type" :value="scope.row.recordType"/>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-info"
              @click="handleInfo(scope.row)"
              v-hasPermi="['base:record:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleAdd(scope.row)"
            v-hasPermi="['base:record:edit']"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改记账记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="记账类型" prop="recordType">
          <el-radio-group v-model="form.recordType">
            <el-radio
              v-for="dict in dict.type.qiu_accounting_record_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="借/还款方式" prop="borrowReturnMethod">
          <el-radio-group v-model="form.borrowReturnMethod">
            <el-radio
              v-for="dict in dict.type.qiu_borrow_return_method"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="交易姓名" prop="borrower">
          <el-input v-model="form.borrower" placeholder="请输入交易姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="borrowerPhone">
          <el-input v-model="form.borrowerPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="昵称" prop="borrowerNick">
          <el-input v-model="form.borrowerNick" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="借/还款时间" prop="borrowReturnTime">
          <el-date-picker clearable
            v-model="form.borrowReturnTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择借/还款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入说明" />
        </el-form-item>


        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 记账记录详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border >
                        <el-descriptions-item label="交易姓名" >{{form.borrower}}</el-descriptions-item>
                        <el-descriptions-item label="昵称" >{{form.borrowerNick}}</el-descriptions-item>
                        <el-descriptions-item label="借/还款时间" >
                          {{ parseTime(form.borrowReturnTime, '{y}-{m}-{d}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="借/还款方式" >
                          <dict-tag :options="dict.type.qiu_borrow_return_method" :value="form.borrowReturnMethod"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="说明" >{{form.description}}</el-descriptions-item>
                        <el-descriptions-item label="记账类型" >
                          <dict-tag :options="dict.type.qiu_accounting_record_type" :value="form.recordType"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="金额" >{{form.amount}}</el-descriptions-item>
                        <el-descriptions-item label="用户ID" >{{form.userId}}</el-descriptions-item>
                        <el-descriptions-item label="部门ID" >{{form.deptId}}</el-descriptions-item>
                        <el-descriptions-item label="联系电话" >{{form.borrowerPhone}}</el-descriptions-item>
                        <el-descriptions-item label="删除标志" >{{form.delFlag}}</el-descriptions-item>
                        <el-descriptions-item label="备注" >{{form.remark}}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的账单数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          <br/><span style="color: red">*注: 借款人、时间、金额一致则更新数据</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/base/record";
import { getToken } from "@/utils/auth";
export default {
  name: "Record",
  dicts: ['qiu_borrow_return_method', 'qiu_accounting_record_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 记账记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 备注时间范围
      daterangeBorrowReturnTime: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/record/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        borrower: null,
        borrowerNick: null,
        borrowReturnTime: null,
        borrowReturnMethod: null,
        description: null,
        recordType: null,
        amount: null,
        userId: null,
        deptId: null,
        borrowerPhone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        borrower: [
          { required: true, message: "交易姓名不能为空", trigger: "blur" }
        ],
        borrowReturnTime: [
          { required: true, message: "借/还款时间不能为空", trigger: "blur" }
        ],
        borrowReturnMethod: [
          { required: true, message: "借/还款方式不能为空", trigger: "change" }
        ],
        description: [
          { required: true, message: "说明不能为空", trigger: "blur" }
        ],
        recordType: [
          { required: true, message: "记账类型不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询记账记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeBorrowReturnTime && '' != this.daterangeBorrowReturnTime) {
        this.queryParams.params["beginBorrowReturnTime"] = this.daterangeBorrowReturnTime[0];
        this.queryParams.params["endBorrowReturnTime"] = this.daterangeBorrowReturnTime[1];
      }
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        borrower: null,
        borrowerNick: null,
        borrowReturnTime: null,
        borrowReturnMethod: null,
        description: null,
        recordType: null,
        amount: 0,
        userId: null,
        deptId: null,
        borrowerPhone: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeBorrowReturnTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(item) {
      if(item.id == null){
        this.reset();
      }else {
        this.form = item;
        this.form.id = null;
      }

      this.open = true;
      this.title = "添加记账记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改记账记录";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "记账记录详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除记账记录编号为"' + ids + '"的数据项？').then(function() {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/record/export', {
        ...this.queryParams
      }, `账单数据表_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "账单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('base/record/importTemplate', {
      }, `账单导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }

  }
};
</script>
